<?php
declare (strict_types = 1);

/*
 *
 *
 * */

namespace app\controller\admin;

use app\model\Config;
use app\model\Role;
use app\model\User;
use think\facade\Validate;
use think\response\Json;
use function app\controller\dump;


class AdminIndex extends AdminBase
{
    //ajax返回值
    public array $result=[
        'code' => 0,
        'msg' => 'success',
        'data' => []
    ];

    /**
     * 显示资源列表
     *
     *
     */
    public function index():string
    {
        //
        $roles = Role::whereIn('id',['1','2'])->column('power');
        dump($roles);
        $mid = [];
        foreach ($roles as $power){
            $mid = array_merge(explode(',',$power),$mid);
        }
        $mid = array_unique($mid);
        $map[] = ['id','in',$mid];
        dump($mid);

        return '';
    }

    public function config(){
        if(cache('?system_config')){
            $config = cache('system_config');
        }else{
            $configs = Config::select()->toArray();
            $config = [];
            if(count($configs)){
                foreach ($configs as $c){
                    $config[$c['var_name']] = $c['type'] > 2 ?addDomain($c['value']):$c['value'];
                }
            }
            cache('system_config',$config,300);
        }

        $this->result['data'] = $config;

        return jJson($this->result);
    }

    /**
     * 验证码
     *
     * */
    public function captcha(){
        $uniqid = uniqid(mt_rand(10000,99999).'');
        $captcha = captcha();
        $key = session('captcha.key');
        cache('ADMIN_CAPTCHA_KEY_'.$uniqid,$key,180);
        $img = "data:image/png;base64," . base64_encode($captcha->getData());
        return json(['token'=>$uniqid,'image'=>$img]);
    }


    /**
     * 显示编辑资源表单页.
     *
     *
     * @return Json
     */
    public function login():Json
    {
        $param = input('param.',[]);
        $param = toUnderline($param);
        try{
            $rule = [
                'user_name' => ['require','regex'=>'/^[\w|\d][\w|\d|@|\.|\_]{3,16}/'],
                'password' => ['require','regex'=>'/[\w|\d|@|\.|\_]{6,16}/'],
                'code' => 'require',
                'token' => 'require',
            ];
            $message = [
                'user_name.require' => '请输入账号',
                'user_name.regex' => '无效的账号格式',
                'password.require' => '请输入密码',
                'password.regex' => '无效的密码格式',
                'code' => '验证码必填',
            ];

            $validate = Validate::rule($rule)->message($message);
            if(!$validate->check($param)){
                throw new \Exception($validate->getError());
            }
            //验证验证码
            $key = cache('ADMIN_CAPTCHA_KEY_'.$param['token']);
            if(!$key){
                throw new \Exception('验证码已失效');
            }
            if(!pv(strtolower($param['code']),$key)){
                throw new \Exception('验证码错误');
            }

            //获取用户信息
            $adminInfo = User::where('username',$param['user_name'])->find();
            if(!$adminInfo){
                throw new \Exception('未注册的账号');
            }
            //验证密码
            if(!pv($param['password'],$adminInfo['password'])){
                throw new \Exception('密码错误，请重新输入');
            }

            //验证状态
            if(!$adminInfo['status']){
                throw new \Exception('您的账号已被冻结，请联系管理员');
            }

            cache('ADMIN_CAPTCHA_KEY_'.$param['token'],null);//清除验证码缓存

            $nt = getDateTime('U');

            $saveData = [
                'ip' => $this->request->ip(),
                'last_login_time' => $nt
            ];

            $adminInfo->save($saveData);

            $tokenData = [
                'uid' => $adminInfo['id'],
                'key' => md5($adminInfo['id'].$saveData['ip'].$nt)
            ];
            $token = encryptCode(serialize($tokenData),'ENCODE',BASE_DOMAIN);
            $headimg = $adminInfo['headimg']?:addDomain('/avatar.jpg');
            $role = '超管';
            if($adminInfo['status'] < 99){
                $roles = Role::whereIn('id',$adminInfo['role_id'])->column('name');
                $role = implode(' ',$roles);
            }
            $this->result['data'] = [
                'token' => $token,
                'user_info' => [
                    'nick_name' => $adminInfo['nickname'],
                    'user_name' => $adminInfo['username'],
                    'photo' => $headimg,
                    'time' => $nt,
                    'role' => $role,
                    'roles' => [],
                    'status' => $adminInfo['status'],
                    'auth_btn_list' => []
                ]
            ];
        }catch (\Exception $e){
            $this->result['code'] = 500;
            $this->result['msg'] = $e->getMessage();
        }
        return jJson($this->result);
    }


}
